//
//  WechatManager.m
//  research
//
//  Created by 章鱼 on 17/3/31.
//  Copyright © 2017年 simon. All rights reserved.
//

#import "WechatManager.h"
#import "AppDelegate.h"
#import "WXApi.h"

@interface WechatManager ()<WXApiDelegate>

@end

@implementation WechatManager

+ (id)defaultManager {
    static WechatManager *weixinMgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        weixinMgr = [[WechatManager alloc] init];
    });
    return weixinMgr;
}

- (id)init {
    self = [super init];
    if (self) {
        _loginCompletionBlock = nil;
        _shareCompletionBlock = nil;
        _userInfoCompletionBlock = nil;
        
        [[AppDelegate shareDelegate] setWxApiDelegate:self];
    }
    return self;
}
- (BOOL)isWeiXinAppInstalled
{
    return [WXApi isWXAppInstalled];
}
- (void)getTokenAndOpenId:(NSString *)code
{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",GYWECHATAppID, GYWECHATAppSecret, code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url            = [NSURL URLWithString:urlStr];
        NSString *urlEncoding = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        NSData *data          = [urlEncoding dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            //解析拿到的数据  调用那个回调函数
            if (data)
            {
                NSDictionary *dic    = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSString *token      = dic[@"access_token"];
                NSString *openId     = dic[@"openid"];
                NSLog(@"%@%@",token,openId);
            }
        });
    });
}
@end
